<template>
  <div>
    <a-row justify="left" style="padding-top: 1rem; padding-bottom: 1rem">
      <a-col span="24">
        <a-form layout="inline" :labelCol="{ span: 6 }">
          <a-form-item
            label="危险源辨识周期"
            :labelCol="{ style: 'width:120px' }"
            :wrapperCol="{ style: 'width:250px' }"
          >
            <a-range-picker
              picker="date"
              v-model:value="searchInfo.tm"
              :allowClear="false"
              valueFormat="YYYY-MM-DD"
              width="250"
            />
          </a-form-item>
          <a-form-item label="单元" :wrapperCol="{ style: 'width:280px' }">
            <a-tree-select
              show-search
              allowClear
              tree-default-expand-all
              :fieldNames="{ label: 'unitname', value: 'unitid', children: 'children' }"
              :tree-data="unitList"
              tree-node-filter-prop="unitname"
              v-model:value="searchInfo.unitid"
            />
          </a-form-item>
          <a-form-item>
            <a-button @click="getResultTableData" type="primary">查询</a-button>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
    <BasicTable
      @register="registerTable"
      size="small"
      title="危险源辨识/隐患上报记录"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 250px)' }"
      :key="mode"
      :dataSource="tableData"
    >
      <template #title="{ column, record }">
        <a v-if="!record.identifyid" @click="onUnitViewButtonClick(record)">{{
          record.unitname
        }}</a>
        <span v-else @click="onViewHazardIdentifyButtonClick(record)">{{ record.title }}</span>
      </template>
      <template #identificationresult="{ column, record }">
        <Tag
          v-if="record.identificationresult !== null && record.identificationresult !== undefined"
          :color="
            identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.color
          "
        >
          {{
            identifyOptions.filter((item) => item.value == record.identificationresult)[0]?.text
          }}</Tag
        >
        <span v-else></span>
      </template>
      <template #ismajor="{ column, record }">
        <div v-if="record.ismajor !== undefined">
          <a-tag v-if="record.ismajor == true" color="#cd201f">重大</a-tag>
          <a-tag v-else-if="record.ismajor == false" color="#3b5999">一般</a-tag>
        </div>
      </template>
      <template #confirmresult="{ column, record }">
        <Tag
          v-if="record.confirmresult !== null && record.confirmresult !== undefined"
          :color="identifyOptions.filter((item) => item.value == record.confirmresult)[0]?.color"
        >
          {{ identifyOptions.filter((item) => item.value == record.confirmresult)[0]?.text }}</Tag
        >
        <span v-else></span>
      </template>
      <template #action="{ column, record }" v-if="mode == 'identify'">
        <TableAction
          v-if="record.identifyid && !record.hasconfirm"
          :actions="[
            {
              icon: 'ant-design:edit-outlined',
              tooltip: '编辑',
              onClick: onEditRecordButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除记录',
                placement: 'left',
                confirm: onDeleteRecordButtonClick.bind(null, record),
              },
            },
          ]"
        />
        <TableAction
          v-else-if="record.identifyid && record.hasconfirm"
          :actions="[
            {
              icon: 'ant-design:check-circle-outlined',
              tooltip: '确认无变化',
              color: 'success',
              popConfirm: {
                title: '是否确认无变化',
                placement: 'left',
                confirm: onNoChangeButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:search-outlined',
              tooltip: '重新辨识',
              onClick: onIdentifyButtonClick.bind(null, record),
            },
          ]"
        />
        <TableAction
          v-else-if="!record.identifyid"
          :actions="[
            // {
            //   icon: 'ant-design:eye-outlined',
            //   onClick: onUnitViewButtonClick.bind(null, record),
            // },
            {
              icon: 'ant-design:file-search-outlined',
              tooltip: '全面辨识',
              onClick: onUnityModeIdentifyButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:insert-row-above-outlined',
              tooltip: '危险源清单',
              onClick: onHazardListButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <UnitViewIdentify @register="registerOnUnitIdentify" :mode="mode" @success="afterSuccess" />
    <IdentifyConfirmModal @register="registerHazardIdentifyInfo" />
    <UnitBasicInfoDrawer @register="registerUnitBasicInfo" />
    <ViewSvgDrawer @register="registerViewSvg" />
    <UpdateIdentifyRecord @register="registerUpdateIdentifyRecord" @success="afterSuccess" />
    <HazardIndentifyModal
      @register="registerHazardOperate"
      @success="afterSuccess"
      :orgcode="organizationCode"
    />
    <HazardInfo @register="registerHazardLogs" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted, nextTick, h, computed } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { unitStatisticsColumn, queryByUnitConditionFormSchema } from './hazard.data';
  const { createMessage } = useMessage();
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import { queryIdentifyRecord, deleteIdentifyRecord, identifyNoChange } from '/@/api/ehs/hazard';
  import { useDrawer } from '/@/components/Drawer';
  import { useRouter } from 'vue-router';
  import { Tag, TreeSelect } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import UnitViewIdentify from './UnitViewIdentify.vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import UnitBasicInfoDrawer from '../unitDivision/UnitBasicInfoDrawer.vue';
  import IdentifyResultStatistic from './IdentifyResultStatistic.vue';
  import ViewSvgDrawer from './ViewSvgDrawer.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import moment from 'moment';
  import IdentifyConfirmModal from './IdentifyConfirmModal.vue';
  const { globalProjectCode } = useGlobSetting();
  import HazardIndentifyModal from './HazardIndentifyModal.vue';
  import UpdateIdentifyRecord from './UpdateIdentifyRecord.vue';
  import HazardInfo from './HazardInfo.vue';
  export default defineComponent({
    name: 'UnitStatistics',
    components: {
      BasicTable,
      TableAction,
      Tag,
      Icon,
      UnitViewIdentify,
      UnitBasicInfoDrawer,
      IdentifyResultStatistic,
      ViewSvgDrawer,
      UpdateIdentifyRecord,
      HazardIndentifyModal,
      IdentifyConfirmModal,
      HazardInfo,
    },
    props: ['mode'],
    setup(props, {}) {
      const searchInfo = ref({
        // isdept: false,
        unitid: null,
        tm: [
          moment().startOf('month').format('YYYY-MM-DD'),
          moment().endOf('month').format('YYYY-MM-DD'),
        ],
      });
      const identifyOptions = ref();
      // 存储当前查询的时间周期范围
      const currenttm = ref(['', '']);
      const tableData = ref([]);
      const projectCode = ref<String>(globalProjectCode);
      const organizationCode = ref();
      const router = useRouter();
      const unitTypeOption = ref([]);
      const unitList = ref([]); // 查询条件中树选择单元的tree数据
      const [registerOnUnitIdentify, { openDrawer: openOnUnityModeIdentifyDrawer }] = useDrawer();
      const [registerHazardIdentifyInfo, { openModal: openHazardIdentifyInfoModal }] = useModal();
      const [registerHazardOperate, { openModal: openHazardOperate }] = useModal();
      const [registerHazardLogs, { openModal: openHazardLogsModal }] = useModal();
      const [registerUnitBasicInfo, { openDrawer: openUnitBasicInfoDrawer }] = useDrawer();
      const [registerViewSvg, { openDrawer: openViewSvgDrawer }] = useDrawer();
      const [registerUpdateIdentifyRecord, { openModal: openUpdateIdentifyRecordModal }] =
        useModal();
      const [registerTable, { expandAll, setLoading }] = useTable({
        columns: unitStatisticsColumn,
        canResize: true,
        showTableSetting: true,
        tableSetting: {
          redo: false,
        },
        striped: false,
        immediate: true,
        showIndexColumn: false,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        indentSize: 25,
        actionColumn: {
          width: 100,
          ifShow: props.mode == 'identify' ? true : false,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      function onDistributionButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源空间分布图',
          operateType: OperationTypeEnum.VIEW,
          svgData: record.bgimg ? JSON.parse(record.bgimg).id : null,
          dataId: record.unitid,
        };
        openViewSvgDrawer(true, propsData);
      }

      function onHazardListButtonClick(record) {
        router.push({
          path: '/ehs/hazard/listview',
          query: {
            unitid: record.unitid,
            mode: props.mode,
          },
        });
      }
      function onUnityModeIdentifyButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源全面辨识',
          operateString: record.unitname + `(${currenttm.value[0] + '~' + currenttm.value[1]})`,
          unitid: record.unitid,
          mode: props.mode,
          begintm: currenttm.value[0],
          endtm: currenttm.value[1],
          orgcode: organizationCode.value,
        };
        openOnUnityModeIdentifyDrawer(true, propsData);
      }
      function onUnitViewButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元基础信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.unitid,
        };
        openUnitBasicInfoDrawer(true, propsData);
      }
      function getResultTableData() {
        setLoading(true);
        let tmp = {
          orgcode: organizationCode.value,
          // isdept: false,
          begintm: searchInfo.value.tm[0],
          endtm: searchInfo.value.tm[1],
          unitid: searchInfo.value.unitid,
          // isconstruction: searchInfo.value.isconstruction,
        };
        queryIdentifyRecord(tmp).then((res) => {
          setLoading(false);
          tableData.value = formatData(res?.items ?? []);
          console.log(tableData.value, res, 'tableDtaa');
          currenttm.value = searchInfo.value.tm;
          //展开全部子集
          nextTick(expandAll);
        });
      }
      function afterSuccess() {
        getResultTableData();
      }

      function formatData(data) {
        let tmp = [];
        tmp = data.map((item) => {
          return {
            ...item.unit,
            children: [...formatData(item?.childs), ...item?.identifys],
          };
        });
        return tmp;
      }

      function onEditRecordButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源辨识/上报隐患',
          operateType: OperationTypeEnum.EDIT,
          operateString: '填报',
          dataId: record.identifyid,
          orgcode: organizationCode.value,
        };
        openUpdateIdentifyRecordModal(true, propsData);
      }

      function onDeleteRecordButtonClick(record) {
        deleteIdentifyRecord(record.identifyid).then((res) => {
          if (res?.success) {
            createMessage.success(res?.msg);
            afterSuccess();
          } else {
            createMessage.error(res?.msg);
          }
        });
      }

      /**
       * 确认无变化
       */
      function onNoChangeButtonClick(record) {
        identifyNoChange(record.hazardid).then((res) => {
          if (res.success) {
            createMessage.success(res.msg);
            afterSuccess();
          } else {
            createMessage.error(res.msg);
          }
        });
      }

      // 打开辨识弹窗
      function onIdentifyButtonClick(record) {
        console.log(record, 'record');
        let propsData: QcUnifyTransToChildProps;
        // 重新辨识
        propsData = {
          moduleName: '危险源辨识/上报隐患',
          operateString: '填报',
          dataId: record.hazardid,
          unitname: record.unitname,
          index: 0,
          unitid: record.unitid,
          hazardList: [],
        };
        openHazardOperate(true, propsData);
      }

      /**
       * 查看危险源辨识信息
       */
      function onViewHazardIdentifyButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源辨识/上报隐患',
          operateString: '查看记录',
          dataId: record.identifyid,
        };
        openHazardIdentifyInfoModal(true, propsData);
      }

      onMounted(() => {
        setLoading(true);
        //  获取枚举类
        queryEnumOptions('EhsUnitTypeEnum,EhsHazardIndentificationResultTypeEnum')
          .then((res) => {
            // console.log('option res', res);
            if (res != undefined && res != null && res.length > 0x0) {
              unitTypeOption.value = res[0].options.map((option) => {
                return {
                  value: Number(option.key),
                  label: option.value,
                };
              });
              const identifyOp = res[1].options.map((option) => {
                return {
                  value: option.key,
                  text: option.value,
                  color: option.attribute.split('"')[3],
                };
              });
              identifyOptions.value = identifyOp;
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });

        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          organizationCode.value = res?.orgcode;
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: res.orgcode,
          }).then((res) => {
            unitList.value = res;
          });
          getResultTableData();
        });
      });
      return {
        moment,
        organizationCode,
        identifyOptions,
        getResultTableData,
        tableData,
        unitList,
        registerViewSvg,
        registerHazardIdentifyInfo,
        registerHazardLogs,
        registerUnitBasicInfo,
        registerOnUnitIdentify,
        registerTable,
        registerUpdateIdentifyRecord,
        searchInfo,
        router,
        unitTypeOption,
        onDistributionButtonClick,
        onUnityModeIdentifyButtonClick,
        onUnitViewButtonClick,
        afterSuccess,
        onHazardListButtonClick,
        onEditRecordButtonClick,
        onDeleteRecordButtonClick,
        onNoChangeButtonClick,
        registerHazardOperate,
        onIdentifyButtonClick,
        onViewHazardIdentifyButtonClick,
      };
    },
  });
</script>

<style scoped>
  a {
    color: #000;
  }
</style>
